
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ServiceModel;
using System.Windows;
using AdventureWorks.Client.Objects;
using AdventureWorks.Services;
using Xomega.Framework;

namespace AdventureWorks.Client.WPF
{
    public partial class EmployeeDetails : Window
    {
        public static void Invoke(Window owner)
        {
            EmployeeDetails frm = new EmployeeDetails();
            frm.Owner = owner;
            frm.isNew = true;
            frm.Show();
        }

        public static void Invoke(Window owner, int kTemporaryKey, int kEmployeeId)
        {
            EmployeeDetails frm = new EmployeeDetails();
            frm.Owner = owner;
            frm.Load(kTemporaryKey, kEmployeeId);
            frm.Show();
        }

        private EmployeeObject obj;
        private bool isNew = false;

        public EmployeeDetails()
        {
            InitializeComponent();
        }

        protected override void OnInitialized(EventArgs e)
        {
            base.OnInitialized(e);

            obj = new EmployeeObject();
            obj.TemporaryKeyProperty.Required = false;
            obj.EmployeeIdProperty.Required = false;
            pnlMain.DataContext = obj;
            gridPayHistory.ItemsSource = obj.PayHistoryList;
            Closing += CheckUnsavedChanges;
        }

        void CheckUnsavedChanges(object sender, CancelEventArgs e)
        {
            bool? modified = obj.IsModified();
            if (modified.HasValue && modified.Value && MessageBox.Show(
                "You have unsaved changes. Do you want to discard them and close the window?",
                "Unsaved Changes", MessageBoxButton.YesNo, MessageBoxImage.Warning,
                MessageBoxResult.No) == MessageBoxResult.No)
                e.Cancel = true;
        }

        private void Load(int kTemporaryKey, int kEmployeeId)
        {
            ErrorList errorList = new ErrorList();
            obj.TemporaryKeyProperty.SetValue(kTemporaryKey);
            obj.EmployeeIdProperty.SetValue(kEmployeeId);
            IEmployeeService svcEmployee = new AdventureWorks.Services.EmployeeService();
            try
            {
                EmployeeKey inRead = new EmployeeKey();
                obj.ToDataContract(inRead);
                Employee_ReadOutput outRead = svcEmployee.Read(inRead);
                obj.FromDataContract(outRead);
            }
            catch(Exception ex)
            {
                errorList.MergeWith(ErrorList.FromException(ex));
            }
            try
            {
                EmployeeKey inPayHistory_ReadList = new EmployeeKey();
                obj.ToDataContract(inPayHistory_ReadList);
                IEnumerable<PayHistory> outPayHistory_ReadList = svcEmployee.PayHistory_ReadList(inPayHistory_ReadList);
                obj.PayHistoryList.FromDataContract(outPayHistory_ReadList);
            }
            catch(Exception ex)
            {
                errorList.MergeWith(ErrorList.FromException(ex));
            }
            try
            {
                if (svcEmployee is IDisposable) ((IDisposable)svcEmployee).Dispose();
            }
            catch(Exception ex)
            {
                errorList.MergeWith(ErrorList.FromException(ex));
            }
            if (errorList.Errors.Count > 0) Errors.Show(errorList);
            btnDelete.IsEnabled = true;
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            // validate the object
            obj.Validate(true);
            ErrorList valErr = obj.GetValidationErrors();
            if (valErr.HasErrors())
            {
                Errors.Show(valErr);
                return;
            }

            try
            {
                IEmployeeService svcEmployee = new AdventureWorks.Services.EmployeeService();
                Employee_UpdateInput inUpdate = new Employee_UpdateInput();
                obj.ToDataContract(inUpdate);
                svcEmployee.Update(inUpdate);
                if (svcEmployee is IDisposable) ((IDisposable)svcEmployee).Dispose();
                obj.SetModified(false, true);
                isNew = false;
                RefreshOwner(false);
                btnDelete.IsEnabled = true;
            }
            catch(Exception ex)
            {
                Errors.Show(ErrorList.FromException(ex));
            }
        }

        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show(
                "Are you sure you want to delete this object?\nThis action cannot be undone.",
                "Delete Confirmation", MessageBoxButton.YesNo, MessageBoxImage.Warning, 
                MessageBoxResult.No) == MessageBoxResult.No) return;

        }

        private void btnClose_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void RefreshOwner(bool activate)
        {
            // TODO: cast to the right form
            EmployeeSearch frm = Owner as EmployeeSearch;
            if (frm != null)
            {
                frm.Refresh();
                if (activate) frm.Activate();
            }
        }
    }
}
